package com.gsma.calendar.android.adapter;

import java.util.ArrayList;
import java.util.Date;

import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.CursorAdapter;
import android.widget.TextView;

import com.gsma.calendar.android.R;
import com.gsma.calendar.android.db.GlobalEventQuery;
import com.gsma.calendar.android.util.Config;

public class GlobalEventAdapter extends CursorAdapter {

	private ArrayList<String> listChecked = new ArrayList<String>();
	private LayoutInflater mInflater;

	public GlobalEventAdapter(Context context, Cursor c) {
		super(context, c, false);
		mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	public ArrayList<String> getListChecked() {
		return listChecked;
	}

	@Override
	public void bindView(View view, final Context context, final Cursor cursor) {
		final GlobalEventViewHolder listItem = (GlobalEventViewHolder) view.getTag();
		final String event_title = getCursor().getString(GlobalEventQuery.EVENT);
		final long start_time = getCursor().getLong(GlobalEventQuery.START_TIME);
		final long end_time = getCursor().getLong(GlobalEventQuery.END_TIME);
		final int is_checked = getCursor().getInt(GlobalEventQuery.ISCHECKED);

		listItem.title.setText(event_title);
		listItem.period.setText(Config.sdf.format(new Date(start_time)) + " - " + Config.sdf.format(new Date(end_time)));

		listItem.checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

//				String event = getCursor().getString(GlobalEventQuery.EVENT);
				boolean sucess = (isChecked) ? listChecked.add(event_title) : listChecked.remove(event_title);
				Log.v("sucess", "" + isChecked + " "+ event_title);

			}
		});
		
		switch (is_checked) {
		case 1:
			listItem.checkBox.setChecked(true);
			break;
		default:
			listItem.checkBox.setChecked(false);
			break;
		}

	}

	@Override
	public View newView(Context context, Cursor cursor, ViewGroup parent) {
		View view = mInflater.inflate(R.layout.list_item_global_event, null);
		final GlobalEventViewHolder listItem = new GlobalEventViewHolder();
		listItem.title = (TextView) view.findViewById(R.id.event_title);
		listItem.period = (TextView) view.findViewById(R.id.period);
		listItem.checkBox = (CheckBox) view.findViewById(R.id.check);

		view.setTag(listItem);
		return view;

	}

	public class GlobalEventViewHolder {
		TextView title;
		TextView period;
		CheckBox checkBox;

	}

}
